<template>
  <!-- 查询表单 -->
  <n-card :bordered="false">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" :showAdvancedButton="false" />
  </n-card>

  <!-- 工种列表 -->
  <n-card :bordered="false" class="mt-3">
    <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
      :action-column="actionColumn" :scroll-x="1090" :striped="true" :showSelection="true"
      @update:checked-row-keys="onCheckedRow">
      <template #tableTitle>
        <n-button type="primary" @click="openModal">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          新建工种类别
        </n-button>
        <n-button type="error" @click="batchDelete" :disabled="checkedRowKeys.length === 0" class="ml-2">
          批量删除
        </n-button>
      </template>
    </BasicTable>
  </n-card>

  <!-- 新增/编辑表单弹窗 -->
  <n-modal v-model:show="showModal" :title="modalTitle" :show-icon="false" preset="dialog">
    <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="100" class="py-4">
      <n-form-item label="工种类别" path="name">
        <n-input placeholder="请输入工种类别" v-model:value="formParams.name" />
      </n-form-item>
      <n-form-item label="状态" path="isActive">
        <n-radio-group v-model:value="formParams.isActive">
          <n-radio :value="true">启用</n-radio>
          <n-radio :value="false">禁用</n-radio>
        </n-radio-group>
      </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="() => (showModal = false)">取消</n-button>
        <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { columns, JobCategoryItem } from './columns';
import { PlusOutlined } from '@vicons/antd';
import { useMessage, useDialog } from 'naive-ui';
import { debounce } from 'lodash-es';

// API
import {
  getFirstLevelCategories,
  addJobCategory,
  updateJobCategory,
  deleteJobCategories,
} from '@/api/position/index';

// --- Refs & Reactive ---
const message = useMessage();
const dialog = useDialog();

// Table
const actionRef = ref<any>(null);
const checkedRowKeys = ref<(string | number)[]>([]);

// Forms & Modals
const showModal = ref(false);
const isEdit = ref(false);
const modalTitle = ref('新建工种类别');
const formBtnLoading = ref(false);
const formRef: any = ref(null);

// Form params for add/edit
const formParams = reactive<Partial<JobCategoryItem>>({
  id: undefined,
  name: '',
  isActive: true,
});

// Form rules
const rules = {
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入工种类别',
  },
  isActive: {
    required: true,
    message: '请选择状态',
  },
};

// --- Form Schema ---
const schemas: FormSchema[] = [
  {
    field: 'name',
    component: 'NInput',
    label: '工种名称',
    componentProps: {
      placeholder: '请输入工种名称',
    },
  },
  {
    field: 'isActive',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '请选择状态',
      options: [
        { label: '启用', value: true },
        { label: '禁用', value: false },
      ],
    },
  },
];

const [register, { getFieldsValue, resetFields }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 100,
  schemas,
  initialValues: {
    name: '',
    isActive: undefined,
  },
});

const handleCheckedRowChange = debounce((keys: (string | number)[]) => {
  checkedRowKeys.value = keys;
}, 50);

const onCheckedRow = (keys: (string | number)[]) => {
  handleCheckedRowChange(keys);
};

// --- Methods ---
// 加载一级工种列表
const loadDataTable = async (params) => {
  const query = {
    ...getFieldsValue(),
    ...params,
  };
  return await getFirstLevelCategories(query);
};

const reloadTable = () => {
  actionRef.value.reload();
};

const handleSubmit = () => {
  reloadTable();
};

const handleReset = () => {
  resetFields();
  reloadTable();
};

// 打开新增弹窗
const openModal = () => {
  isEdit.value = false;
  modalTitle.value = '新建一级工种';
  formParams.id = undefined;
  formParams.name = '';
  formParams.isActive = true;
  showModal.value = true;
};

// --- Action Column Definition  ---
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  align: 'center',
  fixed: 'right',
  render(record: JobCategoryItem) {
    const actionTextMap = { enable: '启用', disable: '禁用' };

    return h(TableAction as any, {
      style: 'text',
      actions: [
        {
          label: '编辑',
          onClick: () => handleEdit(record),
        },
        {
          label: '删除',
          type: 'error',
          onClick: () => handleDelete(record),
        },
      ],
      dropDownActions: [
        {
          label: '启用',
          key: 'enable',
          ifShow: () => !record.isActive,
        },
        {
          label: '禁用',
          key: 'disable',
          ifShow: () => record.isActive,
        },
      ],
      select: (key: string) => {
        const newStatus = key === 'enable';
        const actionText = actionTextMap[key as keyof typeof actionTextMap];

        updateStatus(record, newStatus, actionText!);
      },
    });
  },
});

const updateStatus = async (record: JobCategoryItem, newStatus: boolean, actionText: string) => {
  try {
    const payload = {
      name: record.name,
      jobCategoryId: record.id,
      isActive: newStatus,
    };

    await updateJobCategory(payload);

    message.success(`${actionText}成功`);
    reloadTable();
  } catch (error) {
    message.error(`${actionText}失败，请稍后重试`);
  }
};


// 编辑
const handleEdit = (record: JobCategoryItem) => {
  isEdit.value = true;
  modalTitle.value = '编辑一级工种';
  formParams.id = record.id;
  formParams.name = record.name;
  formParams.isActive = record.isActive;
  showModal.value = true;
};

// 删除单条
const handleDelete = async (record: JobCategoryItem) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除工种【${record.name}】吗？删除后，其下的所有具体工种也将被删除！`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      await deleteJobCategories([record.id]);
      message.success('删除成功');
      reloadTable();
    },
  });
};

// 批量删除
const batchDelete = async () => {
  dialog.warning({
    title: '确认批量删除',
    content: `确定要删除选中的 ${checkedRowKeys.value.length} 条数据吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      await deleteJobCategories(checkedRowKeys.value as number[]);
      message.success('批量删除成功');
      checkedRowKeys.value = [];
      reloadTable();
    },
  });
};

// 提交表单
const confirmForm = async () => {
  formBtnLoading.value = true;
  try {
    await formRef.value.validate();

    const payload: any = {
      jobCategoryId: formParams.id,
      name: formParams.name,
      isActive: formParams.isActive,
    };

    if (isEdit.value) {
      payload.jobCategoryId = formParams.id;
      await updateJobCategory(payload);
      message.success('修改成功');
    } else {
      await addJobCategory(payload);
      message.success('新增成功');
    }

    // 共同的后续操作
    showModal.value = false;
    reloadTable();

  } catch (error: any) {
    if (error !== 'Validate Failed') {
      message.error('操作失败，请稍后重试');
    }
  } finally {
    formBtnLoading.value = false;
  }
};
</script>